package net.suncaper.psychological.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

public class JSONUtil {
    public static void printByJSON(HttpServletResponse response, Object obj) {
        String jsonStr = "";
        if (obj != null && !"".equals(obj)) {
            jsonStr = JSON.toJSONString(obj, 
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
        }
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            out = response.getWriter();
            out.print(jsonStr);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
    
    /**
     * 获取请求体内容
     */
    public static String getRequestBody(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    
    /**
     * 写入JSON响应
     */
    public static void writeJSON(HttpServletResponse response, Object obj) {
        if (obj instanceof Result.JSONResultMap) {
            ((Result.JSONResultMap) obj).writeTo(response);
        } else {
            printByJSON(response, obj);
        }
    }
}
